#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

from cloudutils import CloudUtils
from cloudutils.lib.cmd import Cmd

import os.path
import sys
import platform
import re
import urllib
from urllib2 import urlopen, URLError, HTTPError
import traceback

__version__="1.0"

DhcpDir = {
	'CentOS' : '/var/lib/dhclient',
	'redhat' : '/var/lib/dhclient',
	}

class update(CloudUtils):
	def __init__(self):
		CloudUtils.__init__(self)
		self.command = Cmd(self.logger)
		
	def install(self, params):
		if params.has_key('src'):
			src = params['src']
			filename = os.path.basename(src)
			self.logger.debug("Downloading : %s" % params['src']) 
			target = '/tmp/%s' % filename
			self.download(src, target)
			self.pkgUpdate(target)
			
	def download(self, url, target):
		"""
		download file from url,
		save into target
		@param url : url path
		@param target : local file path
		@return : True/Error raise
		"""

		try:
			#print urllib.urlretrieve(url, target)
			f = urlopen(url)
			print "downloading " + url
			# Open our local file for writing
			local_file = open(target, 'wb')
			#Write to our local file
			local_file.write(f.read())
			local_file.close()
			
		except HTTPError, e:
			self.logger.error("HTTP Error code(%s): URL(%s)" % (e.code, url))
			sys.exit()
		except URLError, e:
			self.logger.error("URL Error reason(%s): URL(%s)" % (e.reason,url))
			sys.exit()
		except:
			self.logger.error(traceback.format_exc())
			sys.exit()

	def pkgUpdate(self, path):
		"""
		install package
		@param path: package file path
		"""
		cmd = ["easy_install", path]
		self.command.run(cmd)
		
		
	
def install(params):
	inst = update()
	inst.install(params)
	
if __name__ == "__main__":
	from optparse import OptionParser
	usage = "usage:%prog [options] arg"
	parser = OptionParser()
	parser.add_option("-s","--sample",dest="sample",help="Sample Config file")
	(options,args) = parser.parse_args()

	inst = installer()
	target='/tmp/cloudconf.cfg'
	if not options.sample:
		inst.install(target)
	inst.callModule(target)
